const { Controller } = require("egg");
const path = require("path");
const fs = require("fs");
const { respAdapter } = require("../../utils");

// const uploadDir = "D:/work/personal/wuyeguanli/attachment/";
const uploadDir = "/web/cat/laorenyuan/attachment/";
const serverPathPrefix = "http://47.120.50.132:16061/attachment/";

class HomeController extends Controller {
  async upload() {
    const { ctx, service } = this;
    // await ctx.multipart(upload, {
    //   fileSize: "5mb" // 限制文件大小
    // }); // 使用上面定义的 Multer 中间件

    const files = ctx.request.files; // 获取上传的文件列表
    console.log("😈files", files);
    if (files && files.length > 0) {
      // 处理上传的文件
      const filePath = files[0].filepath;
      let filename = files[0].filename;
      const buffer = Buffer.from(filename, "utf-8");
      filename = buffer.toString("utf8");
      console.log("😈filePath", filePath);
      // 可以在这里保存文件路径到数据库等操作
      const fileinfo = fs.readFileSync(filePath);
      const name = (+new Date()).toString() + "__" + filename;
      const target = uploadDir + name;
      console.log("😈target", target);
      fs.writeFileSync(target, fileinfo);
      fs.unlinkSync(filePath);

      const resp = await this.app.mysql.insert("attachment", {
        name: filename,
        path: serverPathPrefix + name,
        created_time: new Date(),
        updated_time: new Date()
      });
      console.log("😈resp", resp);

      ctx.body = respAdapter(
        {
          filename,
          // filePath:target,
          path: serverPathPrefix + name,
          id: resp.insertId
        },
        "文件上传成功"
      );
    } else {
      ctx.body = respAdapter({}, "文件上传失败", false);
    }
  }

  async update() {
    const { ctx, app, config } = this;
    const { body } = ctx.request;
    try {
      const token = ctx.headers.authorization
        ? ctx.headers.authorization.split(" ")[1]
        : "";
      await app.jwt.verify(token, config.jwt.secret);

      const resp = await this.app.mysql.update("attachment", body);

      ctx.body = respAdapter({}, null, !!resp);
    } catch (err) {
      ctx.body = respAdapter(null, err, false);
    }
  }
}

module.exports = HomeController;
